<template>
  <div style="width: 100%; height: 200px;" class="center">
    <van-loading size="24px" color="#0094ff" vertical>请稍后...</van-loading>
  </div>
</template>

<script setup>
import { Dialog } from 'vant';
import { onMounted } from "vue";
import { getUserInfoByCode, selectUserByOpenId } from "../api/interface";
import GLOBAL from '../env'
import router from '../router/router';
import store from '../store/store';


// 获取url参数
const  getQueryVariable =() =>{
  var url = location.search; //获取url中"?"符后的字串
  var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1); //substr()方法返回从参数值开始到结束的字符串；
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
        }
    }
    console.log(theRequest);
    return theRequest
}
  // 获取用户信息
const getUserInfo =() =>{
    var params = getQueryVariable();
    if (!params.code) { // 开始授权 获取code
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${GLOBAL.appid}&redirect_uri=${encodeURIComponent(GLOBAL.callBackUrl)}&response_type=code&scope=snsapi_userinfo&state=${Date.now()}#wechat_redirect`
    }else if(params.code){ //根据code获取用户信息及openid
      getUserInfoByCode({
        code:params.code
      }).then((res) =>{
        store.commit("setUserInfo",res.data)
        queryUser(res.data.openid)
      }).catch((err) =>{
        Dialog.alert({
          title: '提示',
          message: 'code获取失败，请联系管理员',
        }).then(() => {
          window.location.replace(GLOBAL.callBackUrl)
        });
      })
    }
}
// 绑定用户 已绑定存在则去主页 否则去绑定界面
const queryUser = (openid)=>{
  selectUserByOpenId({
    openid:openid
  }).then((res) =>{
    if(res.data){
      store.commit("setUserInfo",res.data)
      router.push({path:"/findProject",replace:true})
    }else{
      router.push({path:"/bindPhone",replace:true})
    }
  })
}
onMounted(() => {
    getUserInfo()
});
</script>

<style lang="scss" scoped>
</style>